use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(RoleHasPermissions::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(RoleHasPermissions::PermissionId)
                            .string()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(RoleHasPermissions::RoleId)
                            .string()
                            .not_null(),
                    )
                    .primary_key(
                        Index::create()
                            .col(RoleHasPermissions::PermissionId)
                            .col(RoleHasPermissions::RoleId),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_role_has_permissions_permission_id")
                            .from(RoleHasPermissions::Table, RoleHasPermissions::PermissionId)
                            .to(Permissions::Table, Permissions::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Restrict),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_role_has_permissions_role_id")
                            .from(RoleHasPermissions::Table, RoleHasPermissions::RoleId)
                            .to(Roles::Table, Roles::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Restrict),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(RoleHasPermissions::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum RoleHasPermissions {
    Table,
    PermissionId,
    RoleId,
}

#[derive(DeriveIden)]
enum Permissions {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum Roles {
    Table,
    Id,
}
